class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        for(int i = 0; i < nums.size(); ++i)
        {
            int tgt = -1 * nums[i];
            for(int j = i + 1, k = nums.size() - 1; j < k;)
            {
                if(nums[j] + nums[k] == tgt)
                    ans.push_back({nums[i], nums[j], nums[k]});
                if(nums[j] + nums[k] < tgt)
                    do ++j; while(j < nums.size() && nums[j - 1] == nums[j]);
                else
                    do --k; while(k > 0 && nums[k + 1] == nums[k]);
            }
            while(i + 1 < nums.size() && nums[i] == nums[i + 1]) ++i;
        }
        return ans;
    }
};